package com.jxc.service.impl;

import com.jxc.VO.Attributes;
import com.jxc.mapper.MenuMapper;
import com.jxc.mapper.RoleMenuMapper;
import com.jxc.pojo.Menu;
import com.jxc.pojo.MenuExample;
import com.jxc.pojo.RoleMenu;
import com.jxc.pojo.RoleMenuExample;
import com.jxc.service.MenuService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
@Service
public class MenuServiceImpl implements MenuService {

    @Resource
    private MenuMapper menuMapper;
    @Resource
    private RoleMenuMapper roleMenuMapper;
    @Override
    public List<Menu> selectByExample(Integer pid,Integer roleId) {
        MenuExample menuExample = new MenuExample();
        menuExample.createCriteria().andPIdEqualTo(pid);
        List<Menu> menus = menuMapper.selectByExample(menuExample);
        menusList(menus,roleId);
        return menus;
    }

    private void menusList(List<Menu> menus,Integer roleId) {

        RoleMenuExample roleMenuExample = new RoleMenuExample();
        roleMenuExample.createCriteria().andRoleIdEqualTo(roleId);
        List<RoleMenu> roleMenus = roleMenuMapper.selectByExample(roleMenuExample);
        if(menus != null){
            for (Menu m : menus
            ) {
                if(m.getUrl() != null){
                    Attributes a = new Attributes();
                    a.setUrl(m.getUrl());
                    m.setAttributes(a);
                }
                MenuExample menuExample = new MenuExample();
                menuExample.createCriteria().andPIdEqualTo(m.getId());
                List<Menu> m2 = menuMapper.selectByExample(menuExample);
                if(!m2.isEmpty()){
                    m.setChildren(m2);//赋值
                    for (RoleMenu rm: roleMenus
                    ) {
                        for (Menu m3:m2
                             ) {
                            if(m3.getId().equals(rm.getMenuId())){
                                m3.setChecked(true);
                            }
                        }
                    }
                    menusList(m2,roleId);
                }
            }
        }
    }
}
